<template>
  <div class="content">
    <div class="header">
      企业ID
      <el-input v-model="query.tenantId" placeholder="企业ID" style="width: 200px;margin-right: 5px"
                size="small" @keyup.enter.native="searchChange"></el-input>
      企业名称
      <el-input v-model="query.tenantName" placeholder="企业名称" style="width: 200px;margin-right: 5px"
                size="small" @keyup.enter.native="searchChange"></el-input>
      联系人
      <el-input v-model="query.linkman" placeholder="联系人" style="width: 200px;margin-right: 10px"
                size="small" @keyup.enter.native="searchChange"></el-input>

      <el-button size="small" type="primary" @click="searchChange">
        <i class="el-icon-search"></i>
        搜索
      </el-button>

      <el-button size="small" @click="searchReset">
        <i class="el-icon-delete"></i>
        清空
      </el-button>
    </div>
    <div class="btns">
      <div>
        <el-button size="small" type="primary" @click="addTenant">
          <i class="el-icon-plus"></i>
          新增
        </el-button>
        <el-button size="small" type="danger" plain @click="handleDelete">
          <i class="el-icon-delete"></i>
          删除
        </el-button>
      </div>
    </div>

    <el-table
      :data="data"
      border
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        type="index"
        :index="indexMethod">
      </el-table-column>
      <el-table-column
        prop="tenantId"
        label="企业ID">
      </el-table-column>
      <el-table-column
        prop="tenantName"
        show-overflow-tooltip
        label="企业名称">
      </el-table-column>
      <el-table-column
        prop="linkman"
        label="联系人">
      </el-table-column>
      <el-table-column
        prop="contactNumber"
        show-overflow-tooltip
        label="联系电话">
      </el-table-column>
      <el-table-column
        prop="address"
        show-overflow-tooltip
        label="联系地址">
      </el-table-column>
      <el-table-column
        prop="userNumber"
        label="用户数量">
      </el-table-column>

      <el-table-column
        prop="marketingMailsNumber"
        label="营销邮件同时启动数"
        width="150px">
      </el-table-column>
      <el-table-column
        prop="storageSpace"
        label="系统空间使用量限制(G)"
        width="170px">
      </el-table-column>
      <el-table-column
        prop="socialAutomationNumber"
        label="社交营销开启数量"
        width="150px">
      </el-table-column>
      <el-table-column
        prop="mailAutomationNumber"
        label="邮件营销发送数量"
        width="150px">
      </el-table-column>

      <el-table-column
        prop="emailBindNumlimt"
        label="邮件服务绑定数量限制"
        width="170px">
      </el-table-column>
      <el-table-column
        prop="socialBindNumlimt"
        label="社交账号绑定数量限制"
        width="170px">
      </el-table-column>

      <el-table-column
        prop="validityStartDateTime"
        label="账户有效期开始时间"
        width="150">
      </el-table-column>
      <el-table-column
        prop="validityEndDateTime"
        label="账户有效期结束时间"
        width="150px">
      </el-table-column>
      <el-table-column
        label="营业执照/身份证"
        width="150px">
        <template slot-scope="scope">
          <img :src="scope.row.businessLicensePic" style="max-width: 50px; max-height: 50px;cursor: pointer"
               @click="openImg(scope.row.businessLicensePic)"/>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200px"
        fixed="right">

        <template slot-scope="scope">
          <el-button type="text" @click="view(scope.row)">
            <i class="el-icon-view"></i>
            查看
          </el-button>
          <el-button type="text" @click="edit(scope.row)">
            <i class="el-icon-edit"></i>
            编辑
          </el-button>
          <el-button type="text" @click="removeTenant(scope.row.id)">
            <i class="el-icon-delete"></i>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 15px"
      align="right"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 100]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total">
    </el-pagination>
    <el-dialog :title="dialogTitle"
               :close-on-click-modal="false" :close-on-press-escape	='false'
               :visible.sync="dialogFormVisible" @close="closeDialog">
      <div style="height: 400px;overflow: auto;padding-right: 20px">
        <el-form :model="form" label-width="190px" :rules="rules" ref="form" :disabled="dialogTitle == '查看' ">
          <el-form-item label="企业ID" v-if="dialogTitle == '查看'" :required="true">
            <el-input v-model="form.tenantId" placeholder="请输入 企业ID"></el-input>
          </el-form-item>
          <el-form-item label="企业名称" prop="tenantName">
            <el-input v-model="form.tenantName" placeholder="请输入 企业名称"></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="linkman">
            <el-input v-model="form.linkman" placeholder="请输入 联系人"></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="form.contactNumber" placeholder="请输入 联系电话"></el-input>
          </el-form-item>
          <el-form-item label="联系地址">
            <el-input v-model="form.address" placeholder="请输入 联系地址" type="textarea" minRows="6"></el-input>
          </el-form-item>
          <el-form-item label="用户数量" prop="userNumber">
            <el-input v-model="form.userNumber" placeholder="请输入 用户数量"></el-input>
          </el-form-item>
          <el-form-item label="营销邮件同时启动数" prop="marketingMailsNumber">
            <el-input v-model="form.marketingMailsNumber" placeholder="请输入 营销邮件同时启动数"></el-input>
          </el-form-item>
          <el-form-item label="系统空间使用量限制（G）" prop="storageSpace">
            <el-input v-model="form.storageSpace" placeholder="请输入 系统空间使用量限制"></el-input>
          </el-form-item>
          <el-form-item label="社交营销开启数量" prop="socialAutomationNumber">
            <el-input v-model="form.socialAutomationNumber" placeholder="请输入 社交营销开启数量"></el-input>
          </el-form-item>
          <el-form-item label="邮件营销发送数量" prop="mailAutomationNumber">
            <el-input v-model="form.mailAutomationNumber" placeholder="请输入 邮件营销发送数量"></el-input>
          </el-form-item>
          <el-form-item label="邮件服务绑定数量限制" prop="emailBindNumlimt">
            <el-input v-model="form.emailBindNumlimt" placeholder="请输入 邮件服务绑定数量限制"></el-input>
          </el-form-item>
          <el-form-item label="社交账号绑定数量限制" prop="socialBindNumlimt">
            <el-input v-model="form.socialBindNumlimt" placeholder="请输入 社交账号绑定数量限制"></el-input>
          </el-form-item>

          <el-form-item label="账户有效期开始时间" prop="validityStartDateTime">
            <el-date-picker
              v-model="form.validityStartDateTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请输入 账户有效期开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="账户有效期结束时间" prop="validityEndDateTime">
            <el-date-picker
              v-model="form.validityEndDateTime"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请输入 账户有效期结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="营业执照/身份证" prop="businessLicensePic">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list=false
              accept=".jpeg,.png,.jpg"
              :http-request="uploadFile"
              :multiple=false
              :before-upload="beforeAvatarUpload">
              <img v-if="form.businessLicensePic" :src="form.businessLicensePic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="顶部菜单选择" prop="topMenuid">
            <check-tree @getValue="getVal" ref="checkTree"></check-tree>
          </el-form-item>

        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('form')" size="small" v-if="dialogTitle != '查看'">保 存</el-button>
        <el-button size="small" @click="closeDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {getList, remove, add, getTopMenusCodes, dataInit} from "@/api/system/tenant";
    import checkTree from "@/components/system/checkTree"
    import {uploadOss} from '@/util/file'
    export default {
        name: "tenantElse",
        components: {
            checkTree
        },
        data() {
            return {
                data: [],
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                query: {
                    tenantId: '',
                    tenantName: '',
                    linkman: ''
                },
                header: {},
                dialogTitle: '新增',
                dialogFormVisible: false,
                form: {
                    id: '',
                    tenantId: '',//租户ID
                    tenantName: '',//租户名称
                    linkman: '',//联系人
                    contactNumber: '',//联系电话
                    address: '',//联系地址
                    userNumber: '',//用户数量
                    marketingMailsNumber: '',//营销邮件同时启动数
                    storageSpace: '',//系统空间使用量限制
                    socialAutomationNumber: '',//社交营销开启数量
                    mailAutomationNumber: '',//邮件营销发送数量
                    emailBindNumlimt: '',//邮件服务绑定数量限制
                    socialBindNumlimt: '',//社交服务绑定数量限制
                    validityStartDateTime: '',//账户有效开始时间
                    validityEndDateTime: '',//账户有效结束时间
                    businessLicensePic: '',//营业执照/身份证
                },
                topMenusCodes: [],
                rules: {
                    tenantName: [
                        {required: true, message: '请输入参数名称', trigger: 'blur'}
                    ],
                    linkman: [
                        {required: true, message: '请输入联系人', trigger: 'blur'}
                    ],
                    userNumber: [
                        {required: true, message: '请输入用户数量', trigger: 'blur'}
                    ],

                    marketingMailsNumber: [
                        {required: true, message: '请输入营销邮件同时启动数', trigger: 'blur'}
                    ],
                    storageSpace: [
                        {required: true, message: '请输入系统空间使用量限制', trigger: 'blur'}
                    ],
                    socialAutomationNumber: [
                        {required: true, message: '请输入社交营销开启数量', trigger: 'blur'}
                    ],
                    mailAutomationNumber: [
                        {required: true, message: '请输入邮件营销发送数量', trigger: 'blur'}
                    ],

                    emailBindNumlimt: [
                        {required: true, message: '请输入邮件服务绑定数量限制', trigger: 'blur'}
                    ],
                    socialBindNumlimt: [
                        {required: true, message: '请输入社交账号绑定数量限制', trigger: 'blur'}
                    ],

                    validityStartDateTime: [
                        {required: true, message: '请输入账户有效期开始时间', trigger: 'blur'}
                    ],
                    validityEndDateTime: [
                        {required: true, message: '请输入账户有效期结束时间', trigger: 'blur'}
                    ],
                    businessLicensePic: [
                        {required: true, message: '请输入营业执照/身份证', trigger: 'change'}
                    ]

                },
                selectionList: []
            }
        },
        created() {
            this.init(this.page, this.query)
        },
        computed: {
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        methods: {
            indexMethod(index) {
                return index + 1;
            },
            init(page, params = {}) {
                getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                });
            },
            handleSizeChange(size) {
                this.page.pageSize = size
                this.init(this.page, this.query)
            },
            handleCurrentChange(page) {
                this.page.currentPage = page
                this.init(this.page, this.query)
            },
            searchChange() {
                this.page.currentPage = 1
                this.init(this.page, this.query)
            },
            searchReset() {
                this.query = {};
                this.init(this.page);
            },
            addTenant() {
                this.dialogTitle = '新增'
                this.dialogFormVisible = true;
                this.$nextTick(() => {
                    this.$refs.checkTree.init([]);
                })
            },
            beforeAvatarUpload(file) {
                const isType = file.type == 'image/png' || file.type == 'image/jpeg'
                if (!isType) {
                    this.$message.error('上传图片只能是 JPG, PNG 格式!');
                }
                return isType
            },
            uploadFile(File) {
                let file = File.file;
                uploadOss(file).then(result => {
                    if(result.hasOwnProperty('url')){
                        this.form.businessLicensePic = result.url;
                    }else{
                        this.$message({
                            type: "success",
                            message: '文件上传失败,请重新上传!'
                        })
                    }
                }).catch(err => {
                    this.$message({
                        type: "success",
                        message: '文件上传失败,请重新上传!'
                    })
                })
            },
            submit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let param = Object.assign({}, this.form, {topMenusCodes: this.topMenusCodes})
                        add(param).then((res) => {
                            this.init(this.page)
                            this.dialogFormVisible = false
                        // 请求初始化接口
                            if(!this.form.tenantId) { // 新增的时候tentand为空，初始化数据, 编辑的时候不初始化
                                dataInit(res.data.data).then(res => {
                                    this.$message({
                                        type: "success",
                                        message: res.data.msg
                                    });
                                })
                            }
                        })
                    } else {
                        return false;
                    }
                });
            },
            closeDialog() { // 关闭弹框
                this.form = {
                    id: '',
                    tenantId: '',//租户ID
                    tenantName: '',//租户名称
                    linkman: '',//联系人
                    contactNumber: '',//联系电话
                    address: '',//联系地址
                    userNumber: '',//用户数量
                    marketingMailsNumber: '',//营销邮件同时启动数
                    storageSpace: '',//系统空间使用量限制
                    socialAutomationNumber: '',//社交营销开启数量
                    mailAutomationNumber: '',//邮件营销发送数量
                    emailBindNumlimt: '',//邮件服务绑定数量限制
                    socialBindNumlimt: '',//社交服务绑定数量限制
                    validityStartDateTime: '',//账户有效开始时间
                    validityEndDateTime: '',//账户有效结束时间
                    businessLicensePic: ''//营业执照/身份证
                }
                this.dialogFormVisible = false
            },
            handleSelectionChange(val) {
                this.selectionList = val
            },
            handleDelete() { // 多选删除
                if (this.selectionList.length === 0) {
                    this.$message.warning("请选择至少一条数据");
                    return;
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success"
                }).then(() => {
                    return remove(this.ids);
                }).then(() => {
                    this.init(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                });
            },
            view(item) {
                this.form = item
                this.dialogTitle = '查看'
                this.dialogFormVisible = true
            },
            edit(item) {
                this.form = JSON.parse(JSON.stringify(item))
                this.getTopMenusCodes(item.tenantId)
            },
            getTopMenusCodes(tenantId) {
                getTopMenusCodes(tenantId).then(res => {
                    this.topMenusCodes = []
                    if (res.data.success) {
                        const result = res.data.data;
                        result.map(item => {
                            if (item.status == 1) {
                                this.topMenusCodes.push(item)
                            }
                        })
                        this.dialogTitle = '编辑'
                        this.dialogFormVisible = true;
                        this.$nextTick(() => {
                            this.$refs.checkTree.init(result);
                        })
                    }

                })
            },
            removeTenant(id) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success"
                }).then(() => {
                    return remove(id);
                }).then(() => {
                    this.init(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                });
            },
            openImg(url) {
                window.open(url)
            },
            getVal(checkList, allList) {
                allList.forEach(value => {
                    value.status = 0;
                    if (this.dialogTitle == '新增') {
                        value.id = '';
                    }
                    checkList.forEach(key => {
                        if (value.name == key.name) {
                            value.status = 1
                        }
                    })
                })
                this.topMenusCodes = allList
            }
        }
    }
</script>

<style scoped lang="scss">
  .header {
    margin-bottom: 18px;
  }

  .content {
    background-color: white;
    padding: 20px;
    color: #606266;
    font-size: 13px;
  }

  .btns {
    margin-bottom: 10px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
